package com.gupaoedu.interceptor;

import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Field;
import java.math.RoundingMode;
import java.util.List;
import java.util.Properties;

/**
 * 2020/2/26
 * created by chenpp
 * 拦截Executor的查询方法
 */
@Intercepts({@Signature(type = Executor.class,method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
        , @Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}
)})
public class CPPageInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement  = (MappedStatement) invocation.getArgs()[0];
        BoundSql boundSql = mappedStatement.getBoundSql(invocation.getArgs()[1]);
        String sql = boundSql.getSql();
        StringBuilder sqlBuilder = new StringBuilder(sql);
        RowBounds rowBounds  = (RowBounds) invocation.getArgs()[2];
        //根据参数拼接SQL
        if(rowBounds != null && rowBounds.getLimit() > 0 ){
            if(rowBounds.getOffset() > 0){
                sqlBuilder.append(" limit ").append(rowBounds.getOffset()).append(" , ").append(rowBounds.getLimit());
            }else{
                sqlBuilder.append(" limit ").append(rowBounds.getLimit());
            }
        }
        //MappedStatement里的getBoundSql方法实际调用了里面的sqlSource的getBoundSql方法，所以我们需要通过反射覆盖原来的sqlSource属性
        SqlSource sqlSource = new StaticSqlSource(mappedStatement.getConfiguration(),sqlBuilder.toString(),boundSql.getParameterMappings());
        //将新的SqlSource赋值给原来的SqlSource对象 configuration和ParameterMappings使用原来的就好
        Field field = MappedStatement.class.getDeclaredField("sqlSource");
        field.setAccessible(true);
        field.set(mappedStatement, sqlSource);
        Executor executor = (Executor) invocation.getTarget();
        List list = null;
        if(invocation.getArgs().length == 4){
            list =  executor.query(mappedStatement,invocation.getArgs()[1],new RowBounds(), (ResultHandler) invocation.getArgs()[3]);
        }else{
            list = executor.query(mappedStatement,invocation.getArgs()[1],new RowBounds(), (ResultHandler) invocation.getArgs()[3],(CacheKey)invocation.getArgs()[4], (BoundSql) invocation.getArgs()[5]);
        }
        //sql拼接完成后执行原来的查询方法
        return list;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
